import { Uri , workspace } from "vscode";
import * as Iconv from 'iconv-lite';
// import * as  jschardet from 'jschardet';
import * as path from "path";
import * as fs from "fs";
import languageEncoding from "detect-file-encoding-and-language";

/**
 * 获取文件后缀
 * @param filePath 
 * @returns 
 */
export const getFileExtensionFromPath = (filePath:string) => {
    let arr =  filePath.match(/\.([^.]+)$/)
    return arr && arr[1] ? arr[1].toLowerCase() : "";
}
/**
 * 根据路径获取文件名称
 * @param filePath 
 * @returns 
 */
export const getFileNameFromPath = (filePath:string) => {
    let name = path.basename(filePath);
    return name.split(".")[0];
    
}
/**
 * 获取文件转换成文本
 * @param fsPath 
 * @returns 
 */
export const getFileTextFromPath = async (fsPath:string):Promise<string> => {
    try {
        const buffer = fs.readFileSync(fsPath);
        // console.log("buffer撒旦撒旦撒旦打撒啊倒萨打撒",buffer);
        // const encode = jschardet.detect(buffer).encoding; //获取编码
        const encode =  await getFileEncodingFromPath(fsPath); //获取编码
        const text = Iconv.decode(buffer, encode ? encode : 'utf-8'); //转码后的文本内容
        // console.log("encode",encode)
        // const text = fs.readFileSync(fsPath,{encoding:encode ? encode : 'utf-8'});
        // console.log("text",text)
        return text;
    } catch (error) {
        console.log("error",error);
        return "";
    }  
};
/**
 * 获取文件编码
 * @param fsPath 
 * @returns 
 */
export const getFileEncodingFromPath = (fsPath:string):Promise<BufferEncoding> => {
    return new Promise((resolve,reject) => {
        languageEncoding(fsPath).then((result:any) => {
            resolve(result.encoding);
        }).catch((error) => {
            reject(error);
        });
    });
}



export const divideTheChapter = (content:string) => {
    const regexp = /(?<=\r\n)(\s*)([第序]{1}.*?[章幕卷篇]{1}.*?)(?=\r\n)/g;
    let list:any[] = content.replace(regexp, function($1){
        return "@@@"+$1.trim()+"___";
    }).split("@@@").filter(item => item);
    
    list = list.map(item => {
        let str = item.split("___")[1] ? item.split("___")[0] + " " + item.split("___")[1] : null;
        str = str ? str.trim() : "";
        if(str){
            const index = str.indexOf("\n");
            const title = str.substring(0,index).trim();
            const detail = str.substring(index+1).trim();
            if(title && detail){
                return {
                    title:title,
                    detail:detail
                };
            }
            else{
                return null;
            }
        }
        return null;
    }).filter(item => item);
    return list;


}

/**
 * 检查目录是否存在，没有则创建
 * @param dirPath
 */
export const checkDir = (dirPath:string) => {
    return new Promise<void>((resolve, reject) => {
        dirPath = unifySlashes(dirPath);
        if(fs.existsSync(dirPath)){
            resolve();
        }else{
            reject(new Error("目录无效，请重新设置!"));
        }
    });
};



/**
 * 保存到txt文件
 */
export const saveStringToTxt = (path:Uri,name:string, value: string): Promise<any> => {
    return new Promise((resolve, reject) => {
        const encoder = new TextEncoder();
        workspace.fs.writeFile(Uri.joinPath(path, name + '.txt'), encoder.encode(value)).then(() => {
          resolve(true);
        }, () => {
          resolve(false);
        });
    });
};

/**
 * 将反斜杠转为正斜杠
 * @param str 
 * @returns 
 */
export const unifySlashes = (str:string) => {
    return str.replace(/\\/g, '/');
}


/**
 * utf8ArrayToStr
 * @param array 
 * @returns 
 */
export const utf8ArrayToStr = (array: Uint8Array) => {
    let out, i, c;
    let char2, char3;
    out = "";
    const len = array.length;
    i = 0;
    while(i < len) {
        c = array[i++];
        switch(c >> 4)
        {
        case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7:
            // 0xxxxxxx
            out += String.fromCharCode(c);
            break;
        case 12: case 13:
            // 110x xxxx   10xx xxxx
            char2 = array[i++];
            out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F));
            break;
        case 14:
            // 1110 xxxx  10xx xxxx  10xx xxxx
            char2 = array[i++];
            char3 = array[i++];
            out += String.fromCharCode(((c & 0x0F) << 12) |
                        ((char2 & 0x3F) << 6) |
                        ((char3 & 0x3F) << 0));
            break;
        }
    }
  
    return out;
}


export const generateUniqueID = (length:number) => {
    // 使用Date.now()生成基础的随机数
    let result = Date.now().toString(36);
    // 生成额外的随机数，确保ID的唯一性
    let extra = (Math.random().toString(36) + '0'.repeat(length)).substr(2, length);
    // 拼接两部分结果
    return result + extra;
}


/**
 * 获取系统参数
 */
export const getConfiguration= (key?:string) =>  {
    return key ? workspace.getConfiguration("txt-novel-reading").get(key) : workspace.getConfiguration("txt-novel-reading");
};

/**
 * 设置系统参数
 * @param key 
 * @param data 
 * @returns 
 */
export const setConfiguration = (key:string,data:any) =>  {
    workspace.getConfiguration("txt-novel-reading").update(key,data,true);
    return data;
};